package org.hq.security.service;

import org.hq.security.pojo.DbcUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义 Security UserDetails
 * 系统登录用户账号密码
 * 用于数据库读取账号密码跟
 * web 页面账号密码校验
 *
 */
@Service
public class UserDateilsServiceImpl implements UserDetailsService {
    /**
     * 模拟数据库对象
     */
    private static ConcurrentHashMap<String, DbcUser> dbcusers = new ConcurrentHashMap<String, DbcUser>();
    static {
        dbcusers.put("root",new DbcUser(0,"root","12345","admin","ddddghj"));
        dbcusers.put("he",new DbcUser(0,"he","12345","he,admin","ddddghj"));
        dbcusers.put("qq",new DbcUser(0,"qq","12345","admin","ddddghj"));
        dbcusers.put("heqiao",new DbcUser(0,"heqiao","12345","admin","ddddghj"));
    }


    //密码
    @Autowired
    private PasswordEncoder pw;
    @Override
    @Cacheable
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       System.out.println("用户登录"+username);

        //判断用户是否存在
        if (!dbcusers.containsKey(username)) {
        throw new UsernameNotFoundException("用户不存在"+username);
       }

        //密码加密
        String password = pw.encode(dbcusers.get(username).getPassword());
        //用户配置
        List<GrantedAuthority> Authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(dbcusers.get(username).getGranted());
      User users=  new User(username,password,Authorities);
        return users;
    }
}
